package dfs;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class GenerateParenthesis22 {
    @Test
    public void test() {
        for (int i = 1; i < 5; i++) {
            System.out.println(i);
            System.out.println(generateParenthesis(i));
        }
    }

    // redo at 2022.03.06
    // 注意: 总长度是2n, 不是n.
    public List<String> generateParenthesis(int n) {
        char[] ch = new char[2 * n];
        List<String> results = new ArrayList<>();
        generateRecursively(ch, 0, 0, n, results);
        return results;
    }

    public void generateRecursively(char[] ch, int left, int right, int n, List<String> results) {
        if (left + right == 2 * n) {
            results.add(new String(ch));
        } else {
            int index = left + right;
            if (left < n) {
                ch[index] = '(';
                generateRecursively(ch, left+1, right, n, results);
            }
            if (right < left) {
                ch[index] = ')';
                generateRecursively(ch, left, right+1, n, results);
            }
        }
    }
}
